//SIMMON_ADD
package com.wehealth;


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.net.HttpURLConnection;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import com.umeng.analytics.MobclickAgent;
import com.wehealth.dm.DM_consultationQustion;
import com.wehealth.dm.Doctor;
import com.wehealth.dm.User;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

@SuppressLint({ "ValidFragment", "ShowToast" })
public class ConsultationQestion extends Fragment {
	
	
	private static final int ONLINE_CONSULT  = 0;
	private static final int FREE_CONSULT = 1;
	
	private int mScreen;
	private LinearLayout cons_search;
	private LinearLayout doctor_header;
	private TextView depart_name;
	private String[] departs ;
	private SelectDepartDialog departDialog;
	
	private TextView mTitle ;
	private Doctor mDocktor;
	private String doctorInfo;
	private DM_consultationQustion  mData;
	private EditText  ed_des1;
	private EditText  ed_des2;
	private EditText  ed_des3;
	private MainActivity context;
	private User user;
	private static  String JSONResult;
	private static final int NET_ERROR =-100;
	private static final int NOUSER_ERROR =-101;
	private static final int KESHI_ERROR =-102;
	
	
	public  ConsultationQestion(){
		Log.i("init:", "Message"); 
	}
	
	public  ConsultationQestion(Doctor data,int screen_index){
		mDocktor = data;
		mData = new DM_consultationQustion();
		if(mDocktor !=null){
			doctorInfo = mDocktor.getLevel()+"--"+mDocktor.getRealName()+"   "+"为您服务";
			mData.setDrId(String.valueOf(mDocktor.getID()));
		}
		mScreen = screen_index;
		
		
	

	}
	
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return  inflater.inflate(R.layout.free_consultation, null);
	}
	
	
	
	public void onActivityCreated(Bundle savedInstanceState){
		
		super.onActivityCreated(savedInstanceState);

		
		
		MainActivity activity = (MainActivity)getActivity();
		context = activity;
		
		user = context.getUserInfo();
		Log.d("SIMMON"," user.getUserId()="+user.getUserId());
		mData.setUserId(user.getUserId());
		
		MobclickAgent.openActivityDurationTrack(false);
		
		
		//重点地方
		mTitle = (TextView) activity.findViewById(R.id.header).findViewById(R.id.header_title);
		cons_search =(LinearLayout)activity.findViewById(R.id.cons_search);
		doctor_header =(LinearLayout)activity.findViewById(R.id.doctor_header);
		String title =" " ;
		switch (mScreen) {
				case ONLINE_CONSULT:
					title = getString(R.string.cons_online);
					doctor_header.setVisibility(View.VISIBLE);
					cons_search.setVisibility(View.INVISIBLE);
					TextView serverStr = (TextView)activity.findViewById(R.id.doctor_info);
					serverStr.setText(doctorInfo);
					break;
				case FREE_CONSULT:
					title = getString(R.string.cons_free);
					doctor_header.setVisibility(View.INVISIBLE);
					cons_search.setVisibility(View.VISIBLE);
					break;
				default:
					break;
		 }
		mTitle.setText(title);
		
		departs = activity.getResources().getStringArray(R.array.depart);
		View selct_depart =(View)activity.findViewById(R.id.select_depart_view);
		selct_depart.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				openSelectDepartDialog();		
			}
		});
		
		depart_name = (TextView)activity.findViewById(R.id.depart_name);
		

		//返回主页按钮-------------------------------------------------------//
		 Button bBack = (Button)  activity.findViewById(R.id.header).findViewById(R.id.header_bBack);
			
		 bBack.setOnClickListener(new View.OnClickListener()
			{
				public void onClick(View v)
				{
				    context.switchContentHome();
				}
			});
			
		//------------------------------------------------------------------//
		 
		 //描述 三个地方
		 ed_des1 =(EditText)activity.findViewById(R.id.cons_des1);
	//	 ed_des2 =(EditText)activity.findViewById(R.id.cons_des3);
	//	 ed_des3 =(EditText)activity.findViewById(R.id.cons_des3);
		 
		 
		 
		 ImageView submit = (ImageView)activity.findViewById(R.id.submit_bt);
		 submit.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
			    
			   if(user.getUserId() == -1){
			        openDialog(NOUSER_ERROR);
			    }else if(mData.getkeshiId() == -1){
			        openDialog(KESHI_ERROR);
			    }else {
			    ConsultationToConnServer();
			    }
				
			}
		});
	}
	
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message paramMessage) {
			super.handleMessage(paramMessage);
			
            if(JSONResult!=null){
                BindData(JSONResult);
                JSONResult =null;
            }else{
                //mProgress.setVisibility(View.GONE);
                openDialog(NET_ERROR);
                }
			   // result(paramMessage.what);
		}
	};

	private void ConsultationToConnServer(){
	        new Thread(){
	            @Override
	            public void run(){
	                try {
	                    submitData();
	                } catch (IOException e) {
	                    // TODO Auto-generated catch block
	                    e.printStackTrace();
	                }
	                Message message = new Message();
	                message.what = 0;
	            handler.sendMessage(message);
	            }
	            }.start();
	}
	
	
	
	private void submitData()throws IOException{
		String des1 = ed_des1.getText().toString().trim();
	//	String des2 = ed_des2.getText().toString().trim();
	//	String des3 = ed_des3.getText().toString().trim();
		//http://www.552120.com:8092/Question_Add.aspx?userID=1&drID=0&departmentID=1&amp;description=这里是提问的内容
		String httpUrl = "http://www.552120.com:8092/Question_Add.aspx";
		///com.wehealth.util.GetUrl.SubmitDataUrl();
	   HttpPost httpRequest= new HttpPost(httpUrl);
	     List <NameValuePair> params = new ArrayList <NameValuePair>();
	     String userId = String.valueOf(user.getUserId());
	     params.add(new BasicNameValuePair("userID",userId));
	     params.add(new BasicNameValuePair("drID",mData.getDrId()));
	     String departID = String.valueOf(mData.getkeshiId());
	     params.add(new BasicNameValuePair("departmentID",departID));
	     params.add(new BasicNameValuePair("description",des1));
	     Log.d("SIMMON"," userId= "+userId);
	     Log.d("SIMMON"," drID= "+mData.getDrId());
	     Log.d("SIMMON"," departmentID= "+departID);
	     Log.d("SIMMON"," description= "+des1);
	     try{
	         httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8) );
	         HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
	         if(httpResponse.getStatusLine().getStatusCode() == 200)
	         {
	             
	             JSONResult = EntityUtils.toString(httpResponse.getEntity());
	             Log.d("SIMMON:", "JSONResult="+JSONResult);
	         }
	     } catch(Exception e){
	         Log.e("SIMMON:",  e.toString());
	     }	
	}
	
	
	private void BindData(String strJSON){
	    try{
	            JSONObject jsonObject = new JSONObject(strJSON);
	            String result_str = jsonObject.getString("result");
	            Log.d("SIMMON"," result_str="+result_str);
	            int result = Integer.valueOf(result_str);
	            Log.d("SIMMON"," result="+result); 
	               if(result>0){
	                   openDialog(result);
	                   }
	    }catch(JSONException ex){
	            Log.e("JSON Error: ", ex.toString()); 
	     }
	    
	}
	
	
	
	private void openSelectDepartDialog(){
		MainActivity context = (MainActivity)getActivity();
		DepartListOnItemClickListener  departOnItemClickListener = new DepartListOnItemClickListener();
		 departDialog = new SelectDepartDialog(context,R.style.selectDepartDialog,
				departOnItemClickListener,departs);
		departDialog.setTitle(null);
		departDialog.show();
	}
	
	class DepartListOnItemClickListener implements OnItemClickListener{

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int index,
				long pos2) {
			// TODO Auto-generated method stub
			//科室数据
			mData.setkeshiId(index);
			String name = departs[index];
			depart_name.setText(name);
			departDialog.dismiss();
		}
		
	}
	
    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        MobclickAgent.onPageEnd("ConsultationQestion"); 
    }


    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        MobclickAgent.onPageStart("ConsultationQestion"); 
    }
    
    
    private void openDialog(final int result){
        AlertDialog.Builder builder = new AlertDialog.Builder(context); 
        builder.setIcon(null);
        String login_result = context.getString(R.string.regist_fail);
    
        switch (result) {
        case NOUSER_ERROR:
            login_result = getString(R.string.cons_submit_nouser);
            break;
        case KESHI_ERROR:
            login_result = getString(R.string.cons_submit_keshi);
            break;
        case -1:
            login_result = getString(R.string.cons_submit_fail);
            break;
        case 0:
            login_result = getString(R.string.cons_submit_fail);
            break;
        case NET_ERROR:
            login_result = getString(R.string.net_connet_fail);
            break;
        default:
            if(result > 0){
                login_result = getString(R.string.cons_submit_sucess);
                //mDataManger.delUserDate();
                //user.setUserId(result);
                //mDataManger.storeUserInfo(user);
            }else{
                login_result =getString(R.string.cons_submit_fail);
            }
            break;
    }
         TextView textview = new TextView(context);
         textview.setText(login_result);
         textview.setTextColor(Color.BLACK);
         textview.setTextSize(18);

         textview.setGravity(Gravity.CENTER);
         builder.setView(textview);
         
         
         builder.setPositiveButton("确定", new AlertDialog.OnClickListener() {
             @Override
             public void onClick(DialogInterface arg0, int arg1) {
                 // TODO Auto-generated method stub
                  if(result > 0){
                         Home vHome = new Home();
                         context.switchContent(vHome);           
                  }
             }
             
         });
         builder.create().show();
         
     }
    
    
    

}
